<template>
  <div>
    <van-nav-bar title="登陆" />
    <van-form @submit="onSubmit">
      <van-field
       :loading="iisloading"
        v-model="info.mobile"
        label="手机号"
        placeholder="手机号"
        :rules="rules.mobile"
        @change="sms_code"
      />
      <van-field
        loading-text="发送中"
        v-model="info.code"
        label="验证码"
        placeholder="验证码"
        :rules="rules.code"
      />
      <div style="margin: 16px;">
        <van-button
          :loading="isloading"
          loading-text="登陆中"
          round
          block
          type="info"
          native-type="submit"
          >登陆</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { loginAPI,smsCode } from '@/api'
export default {
  data () {
    return {
      isloading: false,
      iisloading:false,
      info: {
        mobile: '',
        code: ''
      },
      rules: {
        mobile: [
          { pattern: /^1[2-9]\d{9}$/, message: '请填写正确手机号' },
          { required: true, message: '请填写手机号' }
        ],
        code: [
          { pattern: /^\d{4}$/, message: '请填写6位数字验证码' },
          { required: true, message: '请填写验证码' }
        ]
      }
    }
  },
  methods: {
    // 发送短信验证码
    async sms_code (){
      this.iisloading = true
      try {
        const res = await smsCode({"mobile":this.info.mobile})
        console.log('发送验证码的响应',res)
        this.$toast.success('发送成功,请注意查收!!')
      } catch {
        this.$toast.fail("发送失败")
      }
      this.iisloading = false
    },

    //  点击登录  验证短息验证码   验证成功后登录成功
    async onSubmit () {
      this.isloading = true
      try {
        const res = await loginAPI(this.info)
        console.log("登录的响应",res)
        this.$store.commit('changeTokenObj', res.data.data.token)
        console.log("后端生成的token",res.data.data.token)
        console.log("后端生成的refresh_token",res.data.data.refresh_token)
        this.$toast.success('登陆成功')
        this.$store.commit('changeUserInfo', {})
        if (this.$route.query.back) {
          this.$router.push(this.$route.query.back)
        } else {
          this.$router.push('/layout/home')
        }
      } catch {
        this.$toast.fail('登陆失败')
      }
      this.isloading = false
    }
  }
}
</script>

<style></style>
